package net.tbao.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import net.tbao.common.exception.NoStockException;
import net.tbao.common.to.mq.OrderTo;
import net.tbao.common.to.mq.SecKillOrderTo;
import net.tbao.common.utils.R;
import net.tbao.common.vo.MenberResponVO;
import net.tbao.order.constant.OrderConstant;
import net.tbao.order.entity.OrderItemEntity;
import net.tbao.order.entity.PaymentInfoEntity;
import net.tbao.order.enume.OrderStatusEnum;
import net.tbao.order.feign.CartFeignService;
import net.tbao.order.feign.MemberFeignService;
import net.tbao.order.feign.ProductFeignService;
import net.tbao.order.feign.WareFeignService;
import net.tbao.order.interceptor.LonginUserInterceptor;
import net.tbao.order.service.OrderItemService;
import net.tbao.order.service.PaymentInfoService;
import net.tbao.order.to.OrderCreatrTo;
import net.tbao.order.vo.*;
import net.tbao.order.vo.SubmitOrderResponseVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.tbao.common.utils.PageUtils;
import net.tbao.common.utils.Query;

import net.tbao.order.dao.OrderDao;
import net.tbao.order.entity.OrderEntity;
import net.tbao.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    OrderService orderService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor execut;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页返回数据
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();

        MenberResponVO responVO = LonginUserInterceptor.threadLocal.get();

        /**
         * 解决异步任务拿不到ThreadLocal里的数据
         * 获取之前的请求，让每个异步任务的线程共享ThreadLocal数据
         */
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


        CompletableFuture<Void> getAddressTask = CompletableFuture.runAsync(() -> {

            RequestContextHolder.setRequestAttributes(requestAttributes); // 解决异步任务拿不到ThreadLocal里的数据

            // 1、远程查询所有的收货地址
            List<MemberAddressVo> addresses = memberFeignService.getAddress(responVO.getId());
            orderConfirmVo.setAddress(addresses);
        }, execut);

        CompletableFuture<Void> getCartTask = CompletableFuture.runAsync(() -> {

            RequestContextHolder.setRequestAttributes(requestAttributes); // 解决异步任务拿不到ThreadLocal里的数据

            // 2、远程查询购物车所有选中的购物项
            List<OrderItemVo> orderItems = cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setItem(orderItems);
         }, execut).thenRunAsync(() -> {
            // 查询商品是否有库存
            List<OrderItemVo> items = orderConfirmVo.getItem();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasSock(collect);
            List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }

        },execut);


        // 3、用户积分信息
        Integer integration = responVO.getIntegration();
        orderConfirmVo.setIntegration(integration);

        CompletableFuture.allOf(getAddressTask, getCartTask).get(); // 阻塞等待异步任务完成

       //TODO 放入防重复令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + responVO.getId(), token, 30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);
        System.out.println("放入令牌"+orderConfirmVo.getOrderToken());


        return orderConfirmVo;

    }


    /**
     * 下单
     *
     * @param orderSubmitVo
     * @return
     */
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        confirmVoThreadLocal.set(orderSubmitVo);

        SubmitOrderResponseVo submitOrderRespVo = new SubmitOrderResponseVo();
        submitOrderRespVo.setCode(0);

        MenberResponVO memberRespVo = LonginUserInterceptor.threadLocal.get();

        // 判断本次下单的token和redis存储的token是否一致

       //  redis+lua脚本 原子验证令牌防止重复提交攻击
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String redisToken = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
        System.out.println("取出的token"+redisToken);
        //  return 0 失败  1 成功
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), redisToken);
        System.out.println("============"+result);
        if (result == 0l) { // 令牌验证失败
            submitOrderRespVo.setCode(1);
            return submitOrderRespVo;
        } else {// 令牌验证成功
            OrderCreatrTo order = createOrder();

            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 验价通过

                // 保存订单！！！
                saveOrder(order);
                // 锁库存 有异常回滚
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());

                wareSkuLockVo.setLocks(collect);

                // 远程锁库存！！！
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    submitOrderRespVo.setOrder(order.getOrder());
                    // TODO 如果使用的积分优惠，扣减积分

                    // 订单创建成功发送消息
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());

                    return submitOrderRespVo;
                } else {
                    // 锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }

            } else {
                submitOrderRespVo.setCode(2);
                return submitOrderRespVo;
            }
        }
    }

    /**
     * 获取订单状态
     * @return
     */
    @Override
    public OrderEntity getOrderBySn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

        return order_sn;
    }

    /**
     * 关闭订单
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            // 关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);

            // 发送消息给MQ
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);

            // 确保每个消息发送成功，给每个消息做好日志记录，保存每个消息的详细信息
            // 定期扫描数据库，重新发送失败的消息
            try {
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {

            }
        }
    }

    /**
     * 获取当前订单支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderBySn = this.getOrderBySn(orderSn);
        BigDecimal bigDecimal = orderBySn.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderBySn.getOrderSn());
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = order_sn.get(0);
        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(itemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MenberResponVO responVO = LonginUserInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",responVO.getId()).orderByDesc("id"));
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        //修改订单状态信息
        // 2、修改订单状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            // 支付成功
            String orderSn = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(orderSn, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    /**
     * 创建秒杀单的详细信息
     * @param secKillOrderTo
     */
    @Override
    public void createSeckillOrder(SecKillOrderTo secKillOrderTo) {
        //TODO  保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(secKillOrderTo.getOrderSn());
        orderEntity.setMemberId(secKillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = secKillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + secKillOrderTo.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        // TODO 保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(secKillOrderTo.getOrderSn());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(secKillOrderTo.getNum());
        orderItemService.save(itemEntity);
    }

    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreatrTo order) {
        OrderEntity orderEntity=new OrderEntity();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 创建订单号
     * @return
     */
    private OrderCreatrTo createOrder(){

        OrderCreatrTo orderCreatrTo = new OrderCreatrTo();
        //生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        //获取所有订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        orderCreatrTo.setOrder(orderEntity);
        orderCreatrTo.setOrderItems(itemEntities);
        //计算价格相关
        computPrice(orderEntity,itemEntities);


        return orderCreatrTo;
    }

    private void computPrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon=new BigDecimal("0.0");
        BigDecimal integra=new BigDecimal("0.0");
        BigDecimal promotion=new BigDecimal("0.0");
        BigDecimal gift=new BigDecimal("0.0");
        BigDecimal giftIn=new BigDecimal("0.0");

        for (OrderItemEntity entity : itemEntities) {
            coupon= coupon.add(entity.getCouponAmount());
            integra=integra.add( entity.getIntegrationAmount());
            promotion= promotion.add(entity.getPromotionAmount());
            total= total.add(entity.getRealAmount());
            giftIn= giftIn.add(new BigDecimal(entity.getGiftIntegration().toString()));
            gift= gift.add(new BigDecimal(entity.getGiftGrowth().toString()));

        }
        //订单价格相关
        orderEntity.setTotalAmount(total);
        //设置应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));

        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integra);
        orderEntity.setCouponAmount(coupon);

        //设置积分信息
        orderEntity.setIntegration(giftIn.intValue());
        orderEntity.setGrowth(gift.intValue());
        orderEntity.setDeleteStatus(0);



    }

    /**
     * 创建订单号
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        MenberResponVO responVO = LonginUserInterceptor.threadLocal.get();
        OrderEntity entity=new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(responVO.getId());
        //获取收获地址
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        //远程获取收费信息
        R fare = wareFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {});
        //设置运费信息
        entity.setFreightAmount(fareResp.getFare());
        //设置收获人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单状态的相关信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

    /**
     * 构建所有订单项数据
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //获取所有订单项
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if(currentUserCartItems!=null && currentUserCartItems.size()>0){
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity =  buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;

            }).collect(Collectors.toList());
            return itemEntities;
        }
      return null;
    }

    /**
     * 构建某一个订单项数据
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();

        //商品的SPU信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {});
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());

        //商品的Sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());

        //积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //设置订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getPromotionAmount()).subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }


}



